import modelExtend from 'dva-model-extend'
import { findByOrg, addWithOrg, update, enable, disable } from 'services/distributor'
import { lwjPageModel } from 'utils/model'

export default modelExtend(lwjPageModel, {
  namespace: 'distributor',
  state: {
    item: {},
    type: 'create',
    modalVisible: false
  },
  subscriptions: {
    setup ({dispatch, history}) {

    },
  },
  effects: {
    * onChoose ({payload}, {call, put}) {
      const {code} = payload
      if (_.isUndefined(code)) {
        return
      }

      const res = yield call(findByOrg, code)
      yield put({
        type: 'updateItem', payload: {
          item: res.result || {}
        }
      })
    },

    * onStore ({payload}, {call, put}) {
      const {organization, item} = payload
      delete item.version
      const res = yield call(addWithOrg, organization.code, item)

      if (res.success) {
        const result = yield call(findByOrg, organization.code)
        yield put({
          type: 'updateItem', payload: {
            item: result.result
          }
        })
        yield put({
          type: 'hideModal'
        })
      } else {
        throw res
      }
    },

    * onUpdate ({payload}, {call, put}) {
      const {organization, item, id} = payload

      const res = yield call(update, id, item)
      if (res.success) {
        const result = yield call(findByOrg, organization.code)
        yield put({
          type: 'updateItem', payload: {
            item: result.result
          }
        })
        yield put({
          type: 'hideModal'
        })
      } else {
        throw res
      }
    },

    * onModifyEnable ({payload}, {call, put}) {
      const res = payload.enabled ? yield call(disable, payload.id) : yield call(enable, payload.id)

      if (res.success) {
        payload.enabled = !payload.enabled
        yield put({
          type: 'updateItem',
          payload: {item: payload}
        })
      } else {
        throw res
      }
    },
  },
  reducers: {
    updateItem (state, {payload}) {
      state.item = payload.item
      state.type = !payload.item.id ? 'create' : 'update'

      return {
        ...state
      }
    },

    setDistributor (state, {payload}) {
      state.modalVisible = true

      return {
        ...state
      }
    },

    /**
     * 隐藏所有modal
     * @param state
     * @param payload
     * @return {{}}
     */
    hideModal (state, {payload}) {
      state.modalVisible = false

      return {
        ...state
      }
    }
  },
})
